package com.bw.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.Result;
import com.bw.domain.User;
import com.bw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    HttpServletResponse response;

    @Autowired
    RedisTemplate redisTemplate;



    @RequestMapping("/gettime")
    public void gettime()
    {


        Date date = new Date();

        System.out.println(date);


        DateTime newDate2 = DateUtil.offsetDay(date, 3);

        System.out.println(newDate2);
    }





    @RequestMapping("/login")
    public Result login(@RequestBody User user){

       User user1= userService.getuser(user);


        String code = user.getCode();
        if(StrUtil.isBlank(code))
        {
            return Result.fail("请输入验证码");
        }

        String uid = (String) redisTemplate.opsForValue().get(user.getUuid());


        if(!code.equals(uid))
        {
            return Result.fail("验证码错误");
        }


       if(user1==null)
       {
           return Result.fail("用户名错误");
       }

       if(!user1.getPassword().equals(user.getPassword()))
       {
           return Result.fail("密码错误");
       }


       // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiYWRtaW4iOnRydWUsIm5hbWUiOiJsb29seSJ9.



        String token = JWT.create()
                .setPayload("uid",user1.getUserId())
                .setSigner(JWTSignerUtil.none())
                .sign();

        System.out.println(user1.getUserId());


        return Result.success(token);

    }


    @RequestMapping("/getyzm")
    public  void getyzm(String uuid) throws IOException {

        // 自定义纯数字的验证码（随机4位数字，可重复）
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);


        captcha.write(response.getOutputStream());


        // 将验证码存入redis
        redisTemplate.opsForValue().set(uuid,captcha.getCode(),5, TimeUnit.MINUTES);



    }


}
